'use strict';

angular.module('app')
    .controller('zzyLaunchPlanDetailController', ['$rootScope', '$scope', '$http', '$state',
        function ($rootScope, $scope, $http, $state) {
            $scope.title = '投放计划详情';
            $scope.loading = false;
            var adPlanId = $state.params.adPlanId;
            $scope.param = {};
            //详情初始化
            activate(adPlanId);
            //计划下广告初始化
            adSlots(adPlanId);
            // 初始化页面
            function activate(adPlanId) {
                $scope.loading = true;
                $.ajax({
                    url: $scope.app.project_name + '/launchPlan/detail',
                    data: {'adPlanId': adPlanId}
                }).then(function (result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        $scope.record = result.data;
                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }


            // 获取投放计划下的广告
            function adSlots(adPlanId) {
                $scope.loading = true;
                $.ajax({
                    url: $scope.app.project_name + '/launchPlan/adSlots',
                    data: {'adPlanId': adPlanId}
                }).then(function (result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        console.log(result.data);
                        $scope.adSlots = result.data;
                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }



            $scope.approve = function (id, state) {
                if (state == 3) {
                    $scope.param = {};
                    $scope.param.makeUpPlanId = id;
                    $.ajax({
                        url: $scope.app.project_name + '/zzyLaunchPlan/getPlanMakeUp',
                        data: $scope.param
                    }).then(function (result) {
                        if (result.httpCode == 200) {
                            $scope.param = result.data;
                            if (result.data != null) {
                                $("input[name='targetCarriers']").each(function () {
                                    var reg = new RegExp($(this).val(), "g");
                                    if ($scope.param.targetCarriers.match(reg)) {
                                        this.checked = true;
                                    }
                                })

                                if ($scope.chosedCitys.length > 0) {
                                    ($("input[name='targetLocation1']")[1]).checked = true;
                                } else {
                                    ($("input[name='targetLocation1']")[0]).checked = true;
                                }
                                $("input[name='includedIpsets']").each(function () {
                                    if ($(this).val() == $scope.param.includedIpsets) {
                                        this.checked = true;
                                    }
                                })
                                $("input[name='targetDeviceTypes']").each(function () {
                                    var reg = new RegExp($(this).val(), "g");
                                    if ($scope.param.targetDeviceTypes.match(reg)) {
                                        this.checked = true;
                                    }
                                })
                                $("input[name='targetConnectTypes']").each(function () {
                                    var reg = new RegExp($(this).val(), "g");
                                    if ($scope.param.targetConnectTypes.match(reg)) {
                                        this.checked = true;
                                    }
                                })
                                if ($scope.param.dailyExpend == '' || $scope.param.dailyExpend == null || $scope.param.dailyExpend == 9999) {
                                    ($("input[name='dayMoneyNo']")[0]).checked = true;
                                }
                                if ($scope.param.countExpend == '' || $scope.param.countExpend == null || $scope.param.countExpend == 99999) {
                                    ($("input[name='sumMoneyNo']")[0]).checked = true;
                                }
                                $("#dailyExpend").val($scope.param.dailyExpend == 9999 ? "" : $scope.param.dailyExpend);
                                $("#countExpend").val($scope.param.countExpend == 99999 ? "" : $scope.param.countExpend);
                                if ($scope.param.includedIpsets != 0) {
                                    $("#ips").show();
                                    $("#ips").val($scope.param.ips);
                                }
                                ;
                                $scope.isTargetDeviceTypes = ($("input[name='targetDeviceTypes']")[0]).checked;
                                $scope.isTargetConnectTypes = ($("input[name='targetConnectTypes']")[0]).checked;
                                $scope.isTargetCarriers = ($("input[name='targetCarriers']")[0]).checked;
                                $scope.isNoDayMoney = ($("input[name='dayMoneyNo']")[0]).checked;
                                if ($scope.isNoDayMoney) {
                                    $("#dailyExpend").val("");
                                }
                                $scope.isNoSumMoney = ($("input[name='sumMoneyNo']")[0]).checked;
                                if ($scope.isNoSumMoney) {
                                    $("#countExpend").val("");
                                }
                                $scope.$apply();
                            } else {
                                ($("input[name='dayMoneyNo']")[0]).checked = true;
                                ($("input[name='sumMoneyNo']")[0]).checked = true;
                                ($("input[name='targetCarriers']")[0]).checked = true;
                                ($("input[name='targetLocation1']")[0]).checked = true;
                                ($("input[name='includedIpsets']")[0]).checked = true;
                                ($("input[name='targetDeviceTypes']")[0]).checked = true;
                                ($("input[name='targetConnectTypes']")[0]).checked = true;
                                $("#ips").hide();
                                $scope.isTargetDeviceTypes = ($("input[name='targetDeviceTypes']")[0]).checked;
                                $scope.isTargetConnectTypes = ($("input[name='targetConnectTypes']")[0]).checked;
                                $scope.isTargetCarriers = ($("input[name='targetCarriers']")[0]).checked;
                                $scope.isNoSumMoney = ($("input[name='sumMoneyNo']")[0]).checked;
                                $scope.isNoDayMoney = ($("input[name='dayMoneyNo']")[0]).checked;
                                $("#dailyExpend").val("");
                                $("#countExpend").val("");
                                $scope.$apply();
                            }
                            $("#chosedCitysId").hide();
                            getChooesCity(adPlanId);
                            $('#makeUpModel').modal('show', true);
                        } else {
                            $scope.alertModal({"content": "操作失败"});
                        }
                    });
                } else {
                    $scope.param = {};
                    $scope.param.title = "推广计划";
                    $("#title").text($scope.param.title);
                    $scope.param.id = id;
                    $scope.param.type = "PL";
                    $('#refuseUserSupply').modal('show', true);
                }
            }


            $scope.saveMakeUp = function (id) {

                if (($("#dailyExpend").val() == null || $("#dailyExpend").val() == '') && ($("input[name='dayMoneyNo']")[0]).checked == false) {
                    alert("请输入日限额");
                    return;
                }
                if (($("#countExpend").val() == null || $("#countExpend").val() == '') && ($("input[name='sumMoneyNo']")[0]).checked == false) {
                    alert("请输入总限额");
                    return;
                }
                if (($("input[name='targetLocation1']")[1]).checked && $scope.chosedCitys.length == 0) {
                    alert("请选择地域");
                    return;
                }
                if ($("input[name='targetCarriers']:checked").length == 0) {
                    alert("请选择移动运营商定向");
                    return;
                }
                if ($("input[name='includedIpsets']:checked").length == 0) {
                    alert("请选择IP定向");
                    return;
                }
                if ($("input[name='includedIpsets']:checked").length > 0 && $($("input[name='includedIpsets']:checked")[0]).val() != 0 && ($("#ips").val() == '' || $("#ips").val() == null)) {
                    alert("请输入IP");
                    return;
                }
                if($("input[name='includedIpsets']:checked").length > 0 && $($("input[name='includedIpsets']:checked")[0]).val() != 0){
                    var ipsarr = $("#ips").val().split(",");
                    var ipflag = true;
                    var regexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
                    if(ipsarr.length>0){
                        for(var i = 0;i<ipsarr.length;i++){
                            var valid = regexp.test(ipsarr[i]);
                            if(!valid){
                                ipflag = valid;
                                break;
                            }
                        }
                    }else {
                        var valid = regexp.test(ipsarr);
                        ipflag = valid;
                    }
                    if(!ipflag){
                        alert("输入IP格式不正确,请以英文逗号分隔IP");
                        return;
                    }
                }
                if ($("input[name='targetDeviceTypes']:checked").length == 0) {
                    alert("请选择投放设备定向");
                    return;
                }
                if ($("input[name='targetConnectTypes']:checked").length = 0) {
                    alert("请选择移动联网方式定向");
                    return;
                }
                $("#chosedCitysId").show();
                var params = $("#makeUp").serialize();
                $.ajax({
                    url: $scope.app.project_name + '/zzyLaunchPlan/addLaunchPlanMakeup?makeUpPlanId=' + id,
                    data: params
                }).then(function (result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        //详情初始化
                        activate(adPlanId);
                        //计划下广告初始化
                        adSlots(adPlanId);
                        $("#makeUpModel").modal('hide');
                        $scope.alertModal({"content": "操作成功"});
                    } else {
                        $("#makeUpModel").modal('hide');
                        $scope.alertModal({"content": "操作失败"});
                    }
                });
            }

            $scope.approveAd = function (id, state) {
                $scope.alertMessage({
                    text: "确定做此操作吗？", //内容
                    btnCancel: true, //取消按钮
                    btnConfirm: true //确认按钮
                }).then(function () {
                    if (state == 3) {
                        $.ajax({
                            url: $scope.app.project_name + '/launchPlan/approveAd',
                            data: {'id': id, 'state': state}
                        }).then(function (result) {
                            $scope.loading = false;
                            if (result.httpCode == 200) {
                                // //详情初始化
                                // activate(adPlanId);
                                //计划下广告初始化
                                adSlots(adPlanId);
                                $scope.alertModal({"content": "操作成功"});
                            } else {
                                $scope.alertModal({"content": "操作失败"});
                            }
                        });
                    } else {
                        $scope.param = {};
                        $scope.param.title = "广告";
                        $("#title").text($scope.param.title);
                        $scope.param.id = id;
                        $scope.param.type = "AD";
                        $('#refuseUserSupply').modal('show', true);
                    }
                })
            }

            $scope.saveApproveReason = function () {
                var reason = $scope.param.approveReason;
                if (reason == '' || reason == null) {
                    $scope.alertModal({"content": "请输入拒绝原因"});
                    $('#refuseUserSupply').modal('hide');
                    return;
                }
                var url = $scope.param.type == "AD" ? "approveAd" : "approve";
                $.ajax({
                    url: $scope.app.project_name + '/launchPlan/' + url,
                    data: {'id': $scope.param.id, 'state': 4, 'reason': reason}
                }).then(function (result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        // //详情初始化
                        activate(adPlanId);
                        //计划下广告初始化
                        adSlots(adPlanId);
                        $scope.alertModal({"content": "操作成功"});
                    } else {
                        $scope.alertModal({"content": "操作失败"});
                    }
                });
            }

            $scope.addPosArr = {
                "pc": [0, 1, 2, 3, 4, 5, 6, 7, 8],
                "mobile": [0, 1, 2]
            }

            $scope.showPosWrap = function (id) {
                $("#PosWrap" + id).show();
                $("#PosWrap" + id).click(function () {
                    $("#PosWrap" + id).hide();
                })
            }

            $scope.showips = function () {
                if ($("input[name='includedIpsets']:checked").length > 0 && $($("input[name='includedIpsets']:checked")[0]).val() != 0) {
                    $("#ips").show();
                } else {
                    $("#ips").hide();
                }
            }

            //审核
            $scope.submitThirdParty = function (id) {
                $scope.isDisabled = true;
                $scope.alertMessage({
                    text: "确定做此操作吗？", //内容
                    btnCancel: true, //取消按钮
                    btnConfirm: true //确认按钮
                }).then(function () {
                    $.ajax({
                        url: $scope.app.project_name + '/zzyLaunchPlan/submitThirdParty',
                        data: {'id': id}
                    }).then(function (result) {
                        $scope.loading = false;
                        if (result.httpCode == 200) {
                            if ("001" === result.data) {
                                //详情初始化
                                activate(adPlanId);
                                //计划下广告初始化
                                adSlots(adPlanId);
                                $scope.alertModal({"content": "审核成功"});
                                $scope.isDisabled = false;
                            } else if ("002" === result.data) {
                                //详情初始化
                                activate(adPlanId);
                                //计划下广告初始化
                                adSlots(adPlanId);
                                $scope.alertModal({"content": "审核通过,请更新计划"});
                                $scope.isDisabled = false;
                            } else {
                                $scope.alertModal_slow({"content": result.data});
                                $scope.isDisabled = false;
                            }
                        } else {
                            $scope.isDisabled = false;
                        }
                    });
                })
            }

            //确定提交 更新数据
            $scope.updateData = function (id) {
                $scope.isDisabled = true;
                $scope.alertMessage({
                    text: "确定做此操作吗？", //内容
                    btnCancel: true, //取消按钮
                    btnConfirm: true //确认按钮
                }).then(function () {
                    $.ajax({
                        url: $scope.app.project_name + '/zzyLaunchPlan/updatePlanData',
                        data: {'id': id}
                    }).then(function (result) {
                        $scope.loading = false;
                        if (result.httpCode == 200) {
                            if ("001" === result.data) {
                                //详情初始化
                                activate(adPlanId);
                                //计划下广告初始化
                                adSlots(adPlanId);
                                $scope.alertModal({"content": "更新成功"});
                                $scope.isDisabled = false;
                            } else {
                                $scope.alertModal_slow({"content": result.data});
                                $scope.isDisabled = false;
                            }
                        } else {
                            $scope.isDisabled = false;
                        }
                    })
                })
            }

            $scope.openLayer = false;  //控制弹框显现
            //$scope.showAllCitys=false; //控制是否展开省
            $scope.chosedData = [];  //选中的信息集合
            $scope.chosedCitys = [];  //选中的信息集合
            $scope.provinceName = '';
            $scope.cityName = '';
            $scope.backShow = function () {  //回显
                //$scope.chosedId=["10016","10017"]
                angular.forEach($scope.chosedData, function (obj, index) {
                    /*if(obj.region_type===1 || obj.region_type==="1"){
                     angular.forEach($scope.provinces,function(province,Proindex){
                     if(obj.id===province.id){
                     province.ifChosed=true;
                     }
                     })
                     }else if(obj.region_type===2 || obj.region_type==="2"){
                     angular.forEach($scope.citys,function(city,Proindex){
                     if(obj.id===city.id){
                     city.ifChosed=true;
                     }
                     })
                     }else if(obj.region_type===3 || obj.region_type==="3"){
                     angular.forEach($scope.countys,function(county,Proindex){
                     if(obj.id===county.id){
                     county.ifChosed=true;
                     }
                     })
                     }*/
                    angular.forEach($scope.provinces, function (province, Proindex) {
                        if (obj.id === province.id) {
                            province.ifChosed = true;
                        }
                    })
                    angular.forEach($scope.citys, function (city, Proindex) {
                        if (obj.id === city.id) {
                            city.ifChosed = true;
                        }
                    })
                    angular.forEach($scope.countys, function (county, Proindex) {
                        if (obj.id === county.id) {
                            county.ifChosed = true;
                        }
                    })
                })

            }

            $scope.provinces = [];
            $scope.citys = [];
            $scope.countys = [];
            $scope.getDatas = function (parentId) {
                $.ajax({
                    url: $scope.app.project_name + '/zzyLaunchPlan/getChCity',
                    data: {"cityId": parentId}
                }).then(function (res) {
                    console.log(res);
                    if (res.httpCode == 200) {
                        $scope.$apply(function () {
                            angular.forEach(res.data, function (result, index) {
                                result.ifChosed = false;
                                result.ifShowCounty = false;
                                if (result.region_type === 2 || result.region_type === "2") {
                                    $scope.citys.push(result)
                                    $scope.backShow(); //回显
                                } else if (result.region_type === 3 || result.region_type === "3") {
                                    $scope.countys.push(result);
                                    $scope.backShow(); //回显
                                }
                            })

                        })
                    } else {
                        $scope.alertModal({"content": res});
                    }
                })
            }

            /*angular.forEach($scope.provinces,function(result,index){
             result.ifChosed=false;

             })*/

            $scope.showCity = function (province) {
                if (province.ifShowCity == false) {
                    province.ifShowCity = true
                    var countThis = '';  //city中有没有这个parentId的个数
                    if ($scope.citys.length === 0) {
                        $scope.getDatas(province.id)
                    } else {
                        angular.forEach($scope.citys, function (city, index) {
                            if (city.parentId == province.id) {
                                countThis++;
                            }
                        })
                        if (countThis === 0 || countThis == '') {
                            $scope.getDatas(province.id)
                        }
                    }
                } else if (province.ifShowCity == true) {
                    province.ifShowCity = false
                }
            }
            $scope.showCounty = function (city) {
                if (city.ifShowCounty == false) {
                    city.ifShowCounty = true
                    var countThis = '';  //city中有没有这个parentId的个数
                    if ($scope.citys.length === 0) {
                        $scope.getDatas(city.id)
                    } else {
                        angular.forEach($scope.countys, function (county, index) {
                            if (county.parentId == city.id) {
                                countThis++;
                            }
                        })
                        console.log(countThis)
                        if (countThis === 0 || countThis == '') {
                            $scope.getDatas(city.id)
                        }
                    }
                } else if (city.ifShowCounty == true) {
                    city.ifShowCounty = false
                }
            }
            $scope.addprovince = function (thisObj) {
                thisObj.ifChosed = true;
                thisObj.groundParentId = "";
                thisObj.groundParentName = "";
                thisObj.parentId = "";
                thisObj.parentName = "";
                $scope.chosedData.push(thisObj);
            }
            $scope.addcity = function (thisParent, thisObj) {
                // console.log(thisParent)
                thisObj.ifChosed = true;
                thisParent.ifChosed = true;
                thisObj.groundParentId = "";
                thisObj.groundParentName = "";
                thisObj.parentId = thisParent.id;
                thisObj.parentName = thisParent.text;
                $scope.chosedData.push(thisObj);
            }
            $scope.addcounty = function (thisgroundParent, thisParent, thisObj) {
                console.log(thisParent)
                thisObj.ifChosed = true;
                thisParent.ifChosed = true;
                thisgroundParent.ifChosed = true;
                thisObj.groundParentId = thisgroundParent.id;
                thisObj.groundParentName = thisgroundParent.text;
                thisObj.parentId = thisParent.id;
                thisObj.parentName = thisParent.text;
                $scope.chosedData.push(thisObj);
            }

            $scope.cancelChosed = function (thisObject) {
                thisObject.ifChosed = false;
                if (thisObject.region_type === 1 || thisObject.region_type === "1") {
                    angular.forEach($scope.chosedData, function (obj, tdindex) {
                        switch (obj.id) {
                            case thisObject.id:
                                $scope.chosedData.remove($scope.chosedData[tdindex])
                        }
                    })
                } else if (thisObject.region_type === 2 || thisObject.region_type === "2") {
                    angular.forEach($scope.chosedData, function (obj, tdindex) {
                        switch (obj.id) {
                            case thisObject.id:
                                $scope.chosedData.remove($scope.chosedData[tdindex])
                        }
                    })
                } else if (thisObject.region_type === 3 || thisObject.region_type === "3") {
                    angular.forEach($scope.chosedData, function (obj, tdindex) {
                        switch (obj.id) {
                            case thisObject.id:
                                $scope.chosedData.remove($scope.chosedData[tdindex])
                        }
                    })
                }


            }
            $scope.deleteCity = function (index) {
                /*if($scope.chosedData[index].region_type===1 || $scope.chosedData[index].region_type==="1"){
                 angular.forEach($scope.provinces,function(obj,tdindex){
                 switch(obj.id){
                 case $scope.chosedData[index].id:$scope.provinces[tdindex].ifChosed=false;
                 }
                 })
                 }else if($scope.chosedData[index].region_type===2 || $scope.chosedData[index].region_type==="2"){
                 angular.forEach($scope.citys,function(obj,tdindex){
                 switch(obj.id){
                 case $scope.chosedData[index].id:$scope.citys[tdindex].ifChosed=false;
                 }
                 })
                 }else if($scope.chosedData[index].region_type===3 || $scope.chosedData[index].region_type==="3"){
                 angular.forEach($scope.countys,function(obj,tdindex){
                 switch(obj.id){
                 case $scope.chosedData[index].id:$scope.countys[tdindex].ifChosed=false;
                 }
                 })
                 }*/
                angular.forEach($scope.provinces, function (obj, tdindex) {
                    switch (obj.id) {
                        case $scope.chosedData[index].id:
                            $scope.provinces[tdindex].ifChosed = false;
                    }
                })
                angular.forEach($scope.citys, function (obj, tdindex) {
                    switch (obj.id) {
                        case $scope.chosedData[index].id:
                            $scope.citys[tdindex].ifChosed = false;
                    }
                })
                angular.forEach($scope.countys, function (obj, tdindex) {
                    switch (obj.id) {
                        case $scope.chosedData[index].id:
                            $scope.countys[tdindex].ifChosed = false;
                    }
                })

                $scope.chosedData.remove($scope.chosedData[index])
            }

            $scope.deleteAll = function () {
                $scope.chosedData = [];
                angular.forEach($scope.provinces, function (result, index) {
                    result.ifChosed = false;
                })
                angular.forEach($scope.citys, function (result, index) {
                    result.ifChosed = false;
                })
                angular.forEach($scope.countys, function (result, index) {
                    result.ifChosed = false;
                })
            }
            $scope.submit = function () {
                var id_arr = [];
                var id_objArr = [];

                angular.forEach($scope.chosedData, function (obj, index) {
                    if(obj.id){
                        id_arr.push(obj.id);

                    }
                    if(obj.parentId){
                        id_arr.push(obj.parentId);

                    }
                    if(obj.groundParentId){
                        id_arr.push(obj.groundParentId);

                    }

                    if (obj.region_type === 1 || obj.region_type === "1") {
                        id_objArr.push({"province": obj.id, "city": "", "county": ""})
                    } else if (obj.region_type === 2 || obj.region_type === "2") {
                        id_objArr.push({"province": obj.parentId, "city": obj.id, "county": ""})
                    } else if (obj.region_type === 3 || obj.region_type === "3") {
                        id_objArr.push({"province": obj.groundParentId, "city": obj.parentId, "county": obj.id})
                    }

                })
                console.log(id_arr)
                for (var m = 0; m < id_arr.length; m++) {
                    for (var n = m + 1; n < id_arr.length; n++) {
                        if (id_arr[m] === id_arr[n]) {
                            id_arr.splice(m, 1);
                            m--;
                        }
                    }
                }
                // for (var i = 0; i < id_arr.length; i++) {
                //     if (id_arr[i] == undefined || id_arr[i] == "") {
                //         id_arr.splice(i, 1);
                //         i--;
                //     }
                // }
                console.log(id_arr)
                console.log(id_arr);
                $scope.chosedCitys = id_arr;
                console.log(id_objArr);
                $("#diyumodal").hide();
            }
            $scope.showLayer = function (bool) {
                if (bool) {
                    $.ajax({
                        url: $scope.app.project_name + '/zzyLaunchPlan/getChCity',
                        data: {"cityId": 10000}
                    }).then(function (res) {
                        if (res.httpCode == 200) {
                            $scope.$apply(function () {
                                $scope.provinces = res.data;
                                angular.forEach($scope.provinces, function (result, index) {
                                    result.ifChosed = false;  //添加为选中状态
                                    result.ifShowCity = false;  // 添加是否展开市级的状态
                                })
                                $scope.backShow(); //回显
                            })
                        } else {
                            $scope.alertModal({"content": res});
                        }
                    })
                    $("#diyumodal").show();

                } else {
                    $("#diyumodal").hide();
                }
            }
            Array.prototype.remove = function (val) {
                var index = this.indexOf(val);
                if (index > -1) {
                    this.splice(index, 1);
                }
            }

            $scope.changeCheck = function () {
                $scope.isTargetDeviceTypes = ($("input[name='targetDeviceTypes']")[0]).checked;
                $scope.isTargetConnectTypes = ($("input[name='targetConnectTypes']")[0]).checked;
                $scope.isTargetCarriers = ($("input[name='targetCarriers']")[0]).checked;
            }
            $scope.noMoney = function () {
                $scope.isNoDayMoney = ($("input[name='dayMoneyNo']")[0]).checked;
                if ($scope.isNoDayMoney) {
                    $("#dailyExpend").val("");
                }
                $scope.isNoSumMoney = ($("input[name='sumMoneyNo']")[0]).checked;
                if ($scope.isNoDayMoney) {
                    $("#countExpend").val("");
                }
            }
        }]);